package client;

import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.util.Random;


public class Client {

    public static byte[] stringToBytesASCII(String str) {
        char[] buffer = str.toCharArray();
        byte[] b = new byte[buffer.length];
        
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) buffer[i];
        }
        return b;
    }

    public static void main(String... args) throws Exception {
        String hostname = args.length < 1 ? "localhost" : args[0];
        int port = args.length < 2 ? 55555 : Integer.parseInt(args[1]);
        double seconds = args.length < 3 ? 10 : Double.parseDouble(args[2]);

        SocketChannel s = SocketChannel.open(new InetSocketAddress(hostname, port));
        s.configureBlocking(false);
        ByteBuffer bytes = ByteBuffer.allocateDirect(32 * 1024);

        RandomAccessFile aFile = new RandomAccessFile("/mnt/ram1/test.in", "r");
        FileChannel inChannel = aFile.getChannel();

        byte[] b = new byte[8];
        new Random().nextBytes(b);
        s.write(ByteBuffer.wrap(stringToBytesASCII("abcdefgh")));

        while (inChannel.read(bytes) > 0) {
            bytes.flip();
            while (bytes.hasRemaining()) {
                s.write(bytes);
            }
            bytes.clear();
        }

        inChannel.close();
        aFile.close();
        s.close();
    }
}
